<?php
declare (strict_types=1);

namespace app\admin\controller;

use app\common\model\Statistics;
use think\facade\Cache;
use think\facade\View;

class Test extends Base
{
    public function index()
    {
        $task = [
            [
                'title' => '更新统计-每天0点执行一次',
                'type' => 'test1',
                'record' => $this->getRecord('test1')
            ]
        ];
        View::assign([
            'task' => $task
        ]);

        return View::fetch();
    }

    public function getRecord($type)
    {
        $list = Cache::get('task_' . $type);
        if (empty($list)) {
            return [];
        }
        $sort = [];
        foreach ($list as &$v) {
            $sort[] = $v['times'];
        }
        array_multisort($sort, SORT_DESC, $list);

        return $list;
    }

    public function execute()
    {
        try {
            $param = $this->request->post();
            $t1 = microtime(true);
            switch ($param['type']) {
                case 'test1':
                    $result = Statistics::_timing();
                    break;
            }
            $t2 = microtime(true);
            $data['admin'] = $this->admin['admin_name'];
            $data['times'] = time();
            $data['method'] = $this->request->action();
            $data['ip'] = $this->request->ip();
            $data['required'] = round($t2 - $t1, 6);
            $data['status'] = $result['msg'];;
            $list = Cache::get('task_' . $param['type']);
            $list[] = $data;
            Cache::set('task_' . $param['type'], $list);

        } catch (\Exception $e) {

            return json(['code' => -1, 'msg' => $e->getMessage()]);
        }

        return json($result);
    }
}